package router

import (
	"jgt-oper/src/logger"
	"jgt-oper/src/util"
	"jgt-sdk/asapi"

	"github.com/facebookgo/inject"
	"github.com/spf13/viper"
	"github.com/teambition/gear"
)

// ShareRouterV1Handler 初始化share/v1路由
func ShareRouterV1Handler(g *inject.Graph) *gear.Router {
	r := gear.NewRouter(gear.RouterOptions{
		Root:                  "/share/v1",
		IgnoreCase:            true,
		FixedPathRedirect:     true,
		TrailingSlashRedirect: true,
	})

	runMode := viper.GetString("run_mode")
	if runMode == util.ProdMode {
		// 验证令牌
		r.Use(func(ctx *gear.Context) error {
			var traceID string
			if v, err := ctx.Any(util.GetTraceIDKey()); err == nil && v != nil {
				traceID = v.(string)
			}

			token := ctx.GetHeader(util.TokenKey)
			userID := ctx.GetHeader("X-JGT-USERID")
			logger.System(traceID).Infof("访问令牌:%s - 访问用户:%s", token, userID)

			_, err := asapi.GetAPIWithTraceID(traceID).VerifyToken(token)
			if err != nil {
				logger.System(traceID).Infof("验证请求令牌发生错误：%v", err)
				return gear.ErrUnauthorized.WithMsg("无效的授权")
			}

			ctx.SetAny(util.GetUserIDKey(), userID)
			return nil
		})
	}

	ShareUserMap(g, r)
	ShareAuthCodeMap(g, r)
	ShareVisitMap(g, r)

	return r
}
